package com.atguigu.eight;

import com.atguigu.util.RabbitMqUtils;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;

import java.util.HashMap;
import java.util.Map;

/**
 * @author gan
 * @create 2021-07-18 16:06
 *
 * 死信队列
 *
 * 消费者01
 */
public class Consumer01 {

    //普通交换机的名称
    public static final String NORMAL_EXCHANGE = "normal_exchange";

    //死信交换机的名称
    public static final String DEAD_EXCHANGE = "dead_exchange";

    //普通队列的名称
    public static final String NORMAL_QUEUE = "normal_queue";

    //死信队列的名称
    public static final String DEAD_QUEUE = "dead_queue";

    public static void main(String[] args) throws Exception {
        Channel channel = RabbitMqUtils.getChannel();

        //声明死信和普通交换机 类型为direct
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);

        //声明普通队列
        Map<String, Object> arguments = new HashMap<>();
        //过期时间 10s=10000ms
        //这里不设置过期时间，有生产方那边设计会更加灵活
        //arguments.put("x-message-ttl", 10000);

        //正常队列设置死信交换机
        arguments.put("x-dead-letter-exchange", DEAD_EXCHANGE);

        //设置死信RoutingKey
        arguments.put("x-dead-letter-routing-key", "lisi");

        //设置正常队列长度限制
        //表示设置队列的最大长度为6，超过6的消息就会放到死信队列中。
//        arguments.put("x-max-length", 6);

        channel.queueDeclare(NORMAL_QUEUE, false, false, false, arguments);

        //========================================================================

        //声明死信队列
        channel.queueDeclare(DEAD_QUEUE, false, false, false, null);


        //绑定普通交换机与普通队列
        channel.queueBind(NORMAL_QUEUE, NORMAL_EXCHANGE, "zhangsan");

        //绑定死信交换机与死信队列
        channel.queueBind(DEAD_QUEUE, DEAD_EXCHANGE, "lisi");

        System.out.println("Consumer01等待接收消息......");

        DeliverCallback deliverCallback = (consumerTag, message) -> {
            String msg = new String(message.getBody(), "UTF-8");
//            System.out.println(msg);
            if (msg.equals("info5")){
                System.out.println("Consumer01接收的消息是：" + msg + "，此消息是被C1拒绝的");
                //第一个参数表示消息的内容，false表示不将消息放回普通队列，而是放到死信队列中
                channel.basicReject(message.getEnvelope().getDeliveryTag(), false);
            }else {
                System.out.println("Consumer01接收的消息是：" + msg);
                channel.basicAck(message.getEnvelope().getDeliveryTag(), false);
            }

        };

        //死信消息的拒绝要开启手动应答，就是将第二个参数改为false
        channel.basicConsume(NORMAL_QUEUE, false, deliverCallback, consumerTag -> {});
    }
}
